<template>
  <CURDDialog
    ref="CURDModalIns"
    update-title="修改密码"
    :show-options="showOptions"
    :model="pwdSetModel"
    :model-form-setting="pwdSetFormSetting"
    :model-rules="pwdSetRules"
    :curd="curd"
    force-modal
    @close="$emit('update:visible', false)"
  />
</template>
<script setup lang="ts">
import { ref, watch } from "vue";
import { CURDAction, FormItemComponentType, FormItemData, ModelRules, ShowCURDModalOptions } from "./CURDDialog/models";
import { useCURD } from "../hooks/useCURD";
import { RequestMethodEnum } from "../api/req/httpEnum";
import { Api } from "/@/api/main/system";

const props = defineProps<{
  visible: boolean;
  userId?: number;
  hasOldPwd?: boolean;
}>();

defineEmits(["update:visible"]);

const showOptions = ref<ShowCURDModalOptions>();
watch(
  () => props.visible,
  (val) => {
    if (val) {
      showOptions.value = {
        action: CURDAction.UPDATE,
        record: { id: props.userId, userId: props.userId },
        hideNextPrev: true,
      };
    } else {
      showOptions.value = void 0;
    }
  }
);

const { curd } = useCURD({
  updateMethod: RequestMethodEnum.PATCH,
  updateUrl: Api.usersPassword,
  getUpdateConfig(data) {
    return {
      url: Api.usersPassword.replace("{userId}", data.id),
      // headers: {
      //   "Content-Type": "application/x-www-form-urlencoded",
      // },
      params: data,
    };
  },
});

const pwdSetModel = ref(
  props.hasOldPwd
    ? {
        pwd: "",
        password: "",
        repeatPwd: "",
      }
    : {
        password: "",
        repeatPwd: "",
      }
);
const pwdSetFormSetting: FormItemData[] = [
  {
    key: "pwd",
    label: "原始密码",
    required: true,
    type: FormItemComponentType.PASSWORD,
  },
  {
    key: "password",
    label: "新密码",
    required: true,
    type: FormItemComponentType.PASSWORD,
  },
  {
    key: "repeatPwd",
    label: "确认新密码",
    type: FormItemComponentType.PASSWORD,
  },
];
if (!props.hasOldPwd) {
  pwdSetFormSetting.splice(0, 1);
}
const pwdSetRules: ModelRules = [
  {
    repeatPwd: [
      {
        required: true,
        message: "请再输一次密码",
      },
      {
        validator(rule, value) {
          if (value !== pwdSetModel.value.password) {
            return Promise.reject("两次输入的密码不一致");
          }
          return Promise.resolve();
        },
      },
    ],
  },
];
</script>
